
proc toMSB {args} {
    #转换成
    set b0 [expr {((($args)&0x80)!=0)<<0}]
    set b1 [expr {((($args)&0x40)!=0)<<1}]
    set b2 [expr {((($args)&0x20)!=0)<<2}]
    set b3 [expr {((($args)&0x10)!=0)<<3}]

    set b4 [expr {((($args)&0x8)!=0)<<4}]
    set b5 [expr {((($args)&0x4)!=0)<<5}]
    set b6 [expr {((($args)&0x2)!=0)<<6}]
    set b7 [expr {((($args)&0x1)!=0)<<7}]

    set bit [expr {$b0 + $b1 + $b2 + $b3 + $b4 + $b5 + $b6 + $b7}]
    return $bit;
}

proc toMSB16 {args} {
    set hex1 [expr {($args>>0)&0xff}]
    set hex2 [expr {($args>>8)&0xff}]

    set hex1 [toMSB $hex1]
    set hex2 [toMSB $hex2]

    set hex [expr {($hex1<<8)|$hex2}]
    return $hex;
}

proc toMSB24 {args} {
    set hex1 [expr {($args>>0)&0xff}]
    set hex2 [expr {($args>>8)&0xffff}]

    set hex1 [toMSB $hex1]
    set hex2 [toMSB16 $hex2]

    set hex [expr {($hex1<<16)|$hex2}]
    return $hex;
}

proc toMSB32 {args} {
    set hex1 [expr {($args>>0) &0xffff}]
    set hex2 [expr {($args>>16)&0xffff}]

    set hex1 [toMSB16 $hex1]
    set hex2 [toMSB16 $hex2]

    set hex [expr {($hex1<<16)|$hex2}]
    return $hex;
}

proc hex_bit_shift {hex shift} {
    set len [string length $hex]
    set len [expr {$len-1}]
    set str ""
    while {[expr {$len>=0}]} {
        set h4 [string range $hex $len-7 $len]
        set value [format "%x" 0x$h4]
        set value [expr (0x$value>>$shift)&0xffff]
        # puts [format "---%02x" $value]
        set str [format "%02x%s" $value $str]
        incr len -4
    }
    return $str
}

proc hex_to_byte {hex {pos 0}} {
    set len [string length $hex]
    set len [expr {$len-1}]
    set arr {}
    while {[expr {$len>=0}]} {
        set h [string range $hex $len-1 $len]
        # puts输出测试
        # puts $h
        set b [toMSB 0x$h]
        if [expr {$pos<=0}] {
            lappend arr $b
        }
        incr pos -1
        # 下面是转换后的输出测试
        # puts [format "%02x" $b]
        incr len -2
    }
    return $arr
}
